﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using CWB.Common.Constant;
using CWB.Common.DTO;
using CWB.Common.Logging;
using CWB.Common.Utilities;
using CWB.Web.Configuration;
using CWB.Web.DB;
using CWB.Web.Models;
using CWB.Web.Models.Configuration;
using CWB.Web.MVC.BaseController;
using CWB.Web.MVC.Filters;
using CWB.WebSite.Models;
using CWB.WebSite.Models.Agent;
using System.Linq;
using CWB.WebSite.Models.Report;
using System.Globalization;

namespace CWB.WebSite.Controllers.Service
{
    public class RequestServiceController : MultiCultureBaseController
    {
        private static readonly ISysLog Log = SysLog.GetLogger(typeof(RequestServiceController));

        public RequestServiceController(LanguageInfo languageInfo)
            : base(languageInfo)
        {
            ControllerPermision = Permission.Private;
        }

        /// <summary>
        /// Get place order form
        /// </summary>
        /// <param name="sn">which member want to place order.</param>
        /// <returns></returns>
        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult GetOrderForm(int sn)
        {
            DbTableAgent o = new DbTableAgent();
            GetOrderFormModel model = new GetOrderFormModel();

            DbModuleAgent a = o.getAgentbySn(sn);
            if (a.ProdItems != null && a.ProdItems.Count > 0)
            {
                model.ProdItems = a.ProdItems.Select(
                    x => new AgentProdItemViewModel()
                    {
                        prodid = x.prodid,
                        prodName = x.prodName,
                        prodSN = x.prodSN
                    }
                ).ToList();
                model.AgentSN = sn;
                model.Result = ReturnCode.Success;
            }
            else
            {
                model.setException(Err.AgentDoNotHaveAnyProdItem, "GetOrderForm");
            }

            return Json(model, JsonRequestBehavior.DenyGet);
        }

        /// <summary>
        /// reall to place request order.
        /// </summary>
        /// <param name="agentsn"></param>
        /// <param name="prodsn"></param>
        /// <param name="buysell"></param>
        /// <param name="priceask"></param>
        /// <param name="orderunit"></param>
        /// <param name="lm"></param>
        /// <returns></returns>
        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult PlaceRequestOrder(int agentsn, int? prodsn, string buysell, int? priceask, int? orderunit, string lm)
        {

            int iProdSn = Convert.ToInt16(prodsn);
            string sBuySell = buysell ?? "";
            int iPericeAsk = Convert.ToInt16(priceask);
            int iUnit = Convert.ToInt16(orderunit);
            string sLM = lm ?? "";

            ResultBase result = new ResultBase();

            if (!string.IsNullOrEmpty(buysell))
            {
                OrderPosition op = (OrderPosition)Enum.Parse(typeof(OrderPosition), sBuySell);
                //ToDo: need handel using market place order.
                LimitOrMarket limitMarket = (LimitOrMarket)Enum.Parse(typeof(LimitOrMarket), sLM);
                //get agent setting
                DbTableAgent o = new DbTableAgent();
                DbModuleAgent p = o.getAgentbySn(agentsn);
                bool verifiedProd = p.ProdItems.Select(x => x.prodSN == iProdSn).Count() > 0;
                if (verifiedProd)
                {
                    DbModulePlaceOrder dmpo = new DbModulePlaceOrder()
                    {
                        AgentSN = agentsn,
                        Position = op,
                        Price = iPericeAsk,
                        ProdItemSN = iProdSn,
                        Unit = iUnit
                    };
                    DbTableRequestOrder po = new DbTableRequestOrder();
                    PlaceRequestResult rtn = po.CreateRequestOrder(dmpo);

                    switch (rtn)
                    {
                        case PlaceRequestResult.Success:
                            result.Message = Localization.TrandlateMessage(Msg.PlaceOrderSuccess);
                            result.Result = ReturnCode.Success;
                            break;
                        case PlaceRequestResult.Empty:
                            result.setException(Err.RequestOrderResultEmpty, "PlaceRequestOrder");
                            break;
                        case PlaceRequestResult.GeneralError:
                            result.setException(Err.QueryDbGotSynctaxError, "PlaceRequestOrder");
                            break;
                        case PlaceRequestResult.NotInHierarchy:
                            result.setException(Err.TheAccountIsNotUnderYourHierarchy, "PlaceRequestOrder");
                            break;
                        default:
                            result.setException(Err.UnHandelCodeException, "PlaceRequestOrder");
                            break;
                    }
                }
                else
                {
                    result.setException(Err.ProductItemNotSupported, "PlaceRequestOrder");
                }
            }
            else
            {
                result.setException(Err.AskPositionNeedBeChoice, "PlaceRequestOrder");
            }

            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult SearchRequest(int? page, string searchkey, string dtfrom, string dtto)
        {
            int iPage = Convert.ToInt16(page);
            DateTime idtFrom = DateTime.MinValue;
            DateTime idtto = DateTime.MinValue;
            bool paraVerified = true;
            int underAgentSN = 0;
            RequestOrderViewModel result = new RequestOrderViewModel();

            if (sessionData.trading.loginType == LoginType.Agent)
            {
                underAgentSN = sessionData.trading.sn;
            }

            if (!string.IsNullOrEmpty(dtfrom) && !string.IsNullOrEmpty(dtto))
            {
                try
                {
                    CultureInfo ci = new CultureInfo(LanguageInfo.CultureName, false);
                    ci = new CultureInfo("fr-FR", false);
                    idtFrom = DateTime.Parse(dtfrom, ci);
                    idtto = DateTime.Parse(dtto, ci);
                }
                catch (Exception ex)
                {
                    Log.Debug(ex.Message);
                    paraVerified = false;
                    result.setException(new Exception("Date Time format not correct"), "SearchRequest");
                }
            }
            else
            {
                paraVerified = false;
                result.setException(Err.RequestOrderLostStarOrEndDate, "SearchRequest");
            }

            if (paraVerified)
            {
                try
                {
                    DbTableRequestOrder po = new DbTableRequestOrder();
                    Paging pg = new Paging()
                    {
                        currentPage = iPage,
                        pageSize = AppConfigManager.SystemSetting.UsersPageingSize
                    };
                    DBSortingPara dsp = new DBSortingPara();
                    dsp.AddSortingItem("sn", SortingType.Desc);
                    result.RequestOrder = po.SearchRequestOrder(underAgentSN, searchkey, idtFrom, idtto, dsp, ref pg);
                    result.Result = ReturnCode.Success;
                }
                catch (Exception ex)
                {
                    Log.Debug(ex.Message);
                    result.setException(ex, "SearchRequest");
                }
            }
            
            return Json(result, JsonRequestBehavior.DenyGet);
        }


        /*
        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult PlaceRequestOrder(int agentsn, int? prodsn, string buysell, int? priceask, int? orderunit, string lm)
        {

            int iProdSn = Convert.ToInt16(prodsn);
            string sBuySell = buysell ?? "";
            int iPericeAsk = Convert.ToInt16(priceask);
            int iUnit = Convert.ToInt16(orderunit);
            string sLM = lm ?? "";

            ResultBase result = new ResultBase();

            if (!string.IsNullOrEmpty(buysell))
            {
                OrderPosition op = (OrderPosition)Enum.Parse(typeof(OrderPosition), sBuySell);
                //ToDo: need handel using market place order.
                LimitOrMarket limitMarket = (LimitOrMarket)Enum.Parse(typeof(LimitOrMarket), sLM);
                //get agent setting
                DbTableAgent o = new DbTableAgent();
                DbModuleAgent p = o.getAgentbySn(agentsn);
                bool verifiedProd = p.ProdItems.Select(x => x.prodSN == iProdSn).Count() > 0;
                if (verifiedProd)
                {
                    DbModulePlaceOrder dmpo = new DbModulePlaceOrder()
                    {
                        AgentSN = agentsn,
                        Position = op,
                        Price = iPericeAsk,
                        ProdItemSN = iProdSn,
                        Unit = iUnit
                    };
                    DbTablePlaceOrder po = new DbTablePlaceOrder();
                    PlaceOrderResult rtn = po.CreateRequestOrder(dmpo);

                    switch (rtn)
                    {
                        case PlaceOrderResult.Success:
                            result.Result = ReturnCode.Success;
                            result.Message = Localization.TrandlateMessage(Msg.PlaceOrderSuccess);
                            break;
                        case PlaceOrderResult.CannotHaveDifferentPosition:
                            result.Message = Localization.TrandlateMessage(Err.OrderCannotHaveDifferentPosition);
                            break;
                        case PlaceOrderResult.DoNotHaveEnoughtSpaceForPlaceOrder:
                            result.Message = Localization.TrandlateMessage(Err.OrderDoNotHaveEnoughtSpaceForPlaceOrder);
                            break;
                        case PlaceOrderResult.DoNotHaveEnoughtUnit:
                            result.Message = Localization.TrandlateMessage(Err.OrderDoNotHaveEnoughtUnit);
                            break;
                        case PlaceOrderResult.GeneralError:
                            result.setException(Err.PlaceOrderFailed, "PlaceOrder");
                            break;
                        case PlaceOrderResult.NotInHierarchy:
                            result.Message = Localization.TrandlateMessage(Err.TheAccountIsNotUnderYourHierarchy);
                            break;
                        default:
                            result.setException(Err.UnHandelCodeException, "PlaceOrder");
                            break;
                    }
                }
                else
                {
                    result.setException(Err.ProductItemNotSupported, "PlaceOrder");
                }
            }
            else
            {
                result.setException(Err.AskPositionNeedBeChoice, "PlaceOrder");
            }

            return Json(result, JsonRequestBehavior.DenyGet);
        }
         * */

    }
}